package com.itheima.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.system.DeptDao;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.User;
import com.itheima.service.system.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptDao deptDao;

    @Override
    public List<Dept> findAll(String companyId) {
        return deptDao.findAll(companyId);
    }

    @Override
    public void save(Dept dept) {
        deptDao.save(dept);
    }

    @Override
    public Dept findById(String id) {
        return deptDao.findById(id);
    }

    /**
     *  必须消除外键约束
     *  查询部门ID实现细粒度查询
     *  实现了部门修改 且部门id 自动拼接 可以依靠id 来确定父子部门的关系
     * @param dept
     */
    @Override
    public void update(Dept dept) {
//        先删除在添加
        String oldDeptId = dept.getId();
        dept.setId((dept.getParent().getId() == null ? "" : dept.getParent().getId()) + UUID.randomUUID().toString().substring(0, 4));

//        查询到所有的子部门(包括自己)
        List<Dept> depSubList = deptDao.findSubsection(oldDeptId + "%");
        for (Dept subDept : depSubList) {
            if (subDept.getId().equals(oldDeptId)) { // 如果是自己的 不需要重新重新设置ID
                deptDao.deleteById(oldDeptId);
                deptDao.save(dept);
                continue;
            }
            deptDao.deleteById(subDept.getId());
            subDept.setId(subDept.getId().replace(oldDeptId, dept.getId()));
            subDept.getParent().setId(subDept.getParent().getId().replace(oldDeptId, dept.getId()));
            deptDao.save(subDept);
        }


    }

    @Override
    public void deleteById(String id) {
        deptDao.deleteById(id);
    }

    @Override
    public PageInfo findByPage(String companyId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Dept> list = deptDao.findAll(companyId);
        return new PageInfo(list, 10);
    }

    @Override
    public List<Dept> findChildrenDept(String id) {
        return deptDao.findChildrenDept(id);
    }

    @Override
    public List<Dept> findAllNotSub(String companyId,String deptId) {
        List<Dept> deptList = deptDao.findAll(companyId);
        ArrayList<Dept> notSubDeptList = new ArrayList<>();
        for (Dept dept : deptList) {
            if (dept.getId().contains(deptId)){
                continue;
            }
            notSubDeptList.add(dept);
        }
        return notSubDeptList;
    }

    @Override
    public List<User> findByIdUser(String id) {
        return deptDao.findByIdUser(id);
    }
}
